# -*- conding:UTF-8 -*-

'''
@ Project: P8_lxpro_7.7
@ File: auth_app.py
@ Author: 罗婷
@ Date：2022/7/7 14:16

'''
import datetime
import random
import string

import redis
from captcha.image import ImageCaptcha
from flask import Blueprint, Response, jsonify
from flask_restful import Api, Resource, reqparse, marshal
from ronglian_sms_sdk import SmsSDK
from werkzeug.security import generate_password_hash, check_password_hash

from common.celery.tasks import send_sms
from common.model_fields.user_fs import user_fieklds
from common.models import db
from common.models.users import Users
from common.utils.jwtToken_gen_che import generate_token

auth_bp = Blueprint('auth_bp', __name__, url_prefix='/api/v1/auth')
api = Api(auth_bp)

# 生成图片验证码
# class GenerateImage(Resource):
#     def get(self):
#         parser = reqparse.RequestParser()
#         parser.add_argument('uuid')
#         args = parser.parse_args()
#         uuid = args['uuid']
#         print('uuid====', uuid)

        # 生成图片验证码 生成图片 验证码放入图片  UUID放入redis 返回图片
        # text = ''.join(random.sample(string.digits+string.ascii_lowercase, 5))
        # img = ImageCaptcha()
        # image = img.generate(text)
        # if uuid:
        #     rds = redis.Redis()
        #     rds.set(uuid, text, ex=60)
        #     return Response(image)

# 发送短信验证码
# class Send_sms(Resource):
#     def get(self):
#         # 手机号 生成短信验证码  发送  存入redis 返回前端
#         parser = reqparse.RequestParser()
#         parser.add_argument('phone')
#         args = parser.parse_args()
#         mobile = args['phone']
#         print('mobile====', mobile)
#         sms_code = f'{random.randint(10000, 99999)}'
#         res = send_sms.delay(mobile, sms_code)
#         if res:
#             print('短信验证码=====', sms_code)
#             rds = redis.Redis()
#             rds.set(mobile, sms_code, ex=60)
#             return jsonify(message='短信发送成功, 注意查收', code=200)
#         else:
#             return jsonify(message='短信发送失败', code=500)


class Register(Resource):
    # 注册
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('nickname')
        parser.add_argument('mobile')
        parser.add_argument('password')
        parser.add_argument('sms_code')
        args = parser.parse_args()
        nickname = args['nickname']
        mobile = args['mobile']
        password = args['password']
        sms_code = args['sms_code']
        print(f'注册接收到的数据nickname:{nickname}, mobile:{mobile}, password:{password}, sms_code:{sms_code}')
        if not all([nickname, mobile, password, sms_code]):
            return jsonify(message='请完善注册信息', code=400)
        num = Users.query.filter_by(nickname=nickname).count()
        if num > 0:
            return jsonify(message='该用户已注册', code=400)

        rds = redis.Redis()
        code = rds.get(mobile)
        if sms_code != code.decode():
            print(f'填写{sms_code}, 取出{code.decode()}')
            return jsonify(message='验证码错误', code=400)
        try:
            hs_pwd = generate_password_hash(password)
            user = Users(nickname=nickname, mobile=mobile, password=hs_pwd)
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            print(f'添加用户失败{e}')
            return jsonify(message='注册失败', code=500)

        return jsonify(message='注册成功', code=200)
# 登录
class Login(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        parser.add_argument('password')
        args = parser.parse_args()
        mobile = args['mobile']
        password = args['password']
        print(f'注册接收到的数据mobile:{mobile}, password:{password}')
        user = Users.query.filter_by(mobile=mobile).first()
        if not user:
            return jsonify(message='用户未注册', code=400)
        pwd_hash = user.password
        pwd_boll = check_password_hash(pwd_hash, password)
        if pwd_boll:  # 密码通过
            # 生成token
            # 修改登录状态
            Users.query.filter_by(mobile=mobile).update({'online': 1})
            db.session.commit()

            user_data = marshal(user, user_fieklds)
            payload = {'uid': user.id, 'uname': user.nickname, 'mobile': user.mobile}
            token = generate_token(payload)
            if token:
                return jsonify(message='登录成功', code=200, data={
                    'access_token': token,
                    'expires_in': 11232874632453674786,
                    'userInfo': user_data
                })
        else:
            return jsonify(message='密码错误', code=400)

# 找回密码
class FindPwd(Register):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        parser.add_argument('password')
        parser.add_argument('sms_code')
        args = parser.parse_args()
        mobile = args['mobile']
        password = args['password']
        sms_code = args['sms_code']
        print(f'注册接收到的数据mobile:{mobile}, password:{password}, sms_code:{sms_code}')

        rds = redis.Redis()
        code = rds.get(mobile)
        if sms_code != code.decode():
            print(f'填写{sms_code}, 取出{code.decode()}')
            return jsonify(message='验证码错误', code=400)

        # user = Users.query.filter_by(mobile=mobile).first()
        # if not user:
        #     return jsonify(message='用户未注册', code=400)
        pwd_hash = generate_password_hash(password)
        try:
            Users.query.filter_by(mobile=mobile).update({'password': pwd_hash})
            db.session.commit()
        except Exception as e:
            print(f'修改密码错误{e}')
            return jsonify(message='找回密码失败', code=400)
        return jsonify(message='找回密码成功', code=200)



# # 图片验证码
# api.add_resource(GenerateImage, '/code')
# # 发送短信验证码
# api.add_resource(Send_sms, '/phone_code')

# 注册
api.add_resource(Register, '/register')
# 登录
api.add_resource(Login, '/login')
# 找回密码
api.add_resource(FindPwd, '/forget')




